import 'dart:convert';
import 'dart:ui';

import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_add_user_edit_info/bean/company_add_user_edit_info_type.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/change_tab_event.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_attention_widget/special_attention_staff_list_view.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail_search/company_search_detail_list_item_widget.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/bean/edit_user_info_response_bean.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/widgets/person_artificial_attendance_view_model.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'bean/edit_user_upload_bean.dart';

class EditUserPageViewModel extends BaseViewModel {
  ///App用户详情
  static const String USER_INFO_API =ServerApi.BASE_URL + "app/appFaceUserInfo";

  ///App删除用户
  static const String DELETE_USER_API =ServerApi.BASE_URL + "app/appRmoveUser";

  ///用户重复
  static final String _USER_REPEAT = "700";

  ///手机号重复
  static final String _PHONE_REPEAT = "701";

  ///用户重复
  static final String _NICK_REPEAT = "702";

  VoidCallback onPushNameRepeat;

  ValueNotifier<PersonDetailResponseBean> infoValueNotifier;
  ValueNotifier<EditUserInfoDataBean> userInfoValueNotifier;

  EditUserPageViewModel(BaseState state) : super(state) {
    infoValueNotifier = ValueNotifier(null);
    userInfoValueNotifier = ValueNotifier(null);
    if (state!=null&&state is EditUserPageState) {
      onPushNameRepeat = state.pushNameRepeatDialog;
    }
  }

  //删除用户
  void deleteUserHttp(BuildContext context,
      {String fuid, String roleid, String userid,String pages}) {
    if (StringUtils.isEmpty(fuid)) {
      VgToastUtils.toast(context, "人员获取信息错误");
      return;
    }
    if (StringUtils.isEmpty(roleid)) {
      VgToastUtils.toast(context, "身份错误");
      return;
    }
    VgHudUtils.show(context, "删除中");
    VgHttpUtils.get(DELETE_USER_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fuid": fuid ?? "",
          "roleid": roleid ?? "",
          "userid": userid ?? ""
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          String searchDetailKey = SP_SEARCH_DETAIL+UserRepository.getInstance().getCompanyId();
          //查询缓存，缓存中有数据，在基础上删除
          SharePreferenceUtil.getString(searchDetailKey).then((userJsonStr){
            if(userJsonStr == null){
              return;
            }
            var listDynamic = jsonDecode(userJsonStr);
            List<Map<String ,dynamic>>  map = List<Map<String ,dynamic>>.from(listDynamic);
            List<CompanyDetailByTypeListItemBean> M = new List();
            map.forEach((element) => M.add(CompanyDetailByTypeListItemBean.fromMap(element)));
            List<String> fuids = List<String>();
            M?.forEach((element) {
              fuids?.add(element?.fuid);
            });
            if(fuids?.toString()?.contains(fuid)){
              // itemBeanListSearch = M;
              for(int i = 0;i<M.length ; i++){
                if(fuid == M[i]?.fuid){
                  M?.removeAt(i);
                }
              }
              String cache = jsonEncode(M);
              SharePreferenceUtil.putString(searchDetailKey, cache);
              VgEventBus.global.send(SearchRefreshEvent());
            }
          });
          VgEventBus.global.send(new ArtificialAttendanceUpdateEvent());//根更新主页管理数
          //刷新
          // VgEventBus.global.send(MultiDelegeRefreshEvent());
          //更新企业主页数
          VgEventBus.global.send(CompanyNumBarEventMonitor());
          if(pages == "CheckInStatisticsPage"){
            RouterUtils.popUntil(context,"CheckInStatisticsPage");
          }else if(pages == "AttendRecordCalendarPage"){
            RouterUtils.popUntil(context,"CheckInStatisticsPage");
          }else if(pages == "CompanyDetailSearchPage") {
            RouterUtils.popUntil(context, "CompanyDetailSearchPage");
          } else if(pages == "CheckInRecHistoryPage"){
            RouterUtils.popUntil(context,"CheckInRecHistoryPage");
          }else if(pages == "ClassOrDepartmentDetail"){
            RouterUtils.popUntil(context,"ClassOrDepartmentDetail");
          }else{
            RouterUtils.popUntil(context,"CompanyDetailPage");
          }

        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  @override
  void onDisposed() {
    userInfoValueNotifier.dispose();
    infoValueNotifier?.dispose();
    super.onDisposed();
  }

  ///获取用户信息请求
  void getUserInfoBean(String fuid) {
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appTodayGroupPersonDetails",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "current": 1,
          "size": 1000,
          "fuid": fuid ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          PersonDetailResponseBean bean = PersonDetailResponseBean.fromMap(val);
          // EditUserInfoResponseBean bean = EditUserInfoResponseBean.fromMap(val);
          infoValueNotifier.value = bean;
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///获取用户信息请求
  void getUserInfoHttp(String fuid) {
    VgHttpUtils.get(USER_INFO_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fuid": fuid ?? "",
        },
        callback: BaseCallback(onSuccess: (val) {
          EditUserInfoResponseBean bean = EditUserInfoResponseBean.fromMap(val);
          userInfoValueNotifier.value = bean?.data;
        }, onError: (msg) {
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///编辑后保存用户请求
  void saveUserHttp(BuildContext context, EditUserUploadBean uploadBean,String groupid, {VoidCallback logout, VoidCallback onSuccess}) async {
    if (uploadBean == null) {
      VgToastUtils.toast(context, "上传信息获取失败");
      return;
    }
    if (StringUtils.isNotEmpty(uploadBean?.phone) &&
        !VgToolUtils.isPhone(uploadBean?.phone)) {
      VgToastUtils.toast(context, "手机号不正确");
      return;
    }
    VgHudUtils.show(context, "保存中");
    if (StringUtils.isNotEmpty(uploadBean.headFaceUrl) &&
        !VgStringUtils.isNetUrl(uploadBean.headFaceUrl)) {
      try {
        String netFace = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            uploadBean.headFaceUrl, isFace: true);
        if (StringUtils.isNotEmpty(netFace)) {
          uploadBean.headFaceUrl = netFace;
        } else {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "上传头像失败");
          return;
        }
      } catch (e) {
        VgHudUtils.hide(context);

        VgToastUtils.toast(context, "上传头像失败");
        return;
      }
    }
    if (uploadBean.identityType == CompanyAddUserEditInfoIdentityType.superAdmin) {
      //超管时清空终端 部门 班级 （不用上传）
      uploadBean.departmentList = null;
      uploadBean.classIdList = null;
      uploadBean.terminalList = null;
    }
    //      "defaultMessage": "Failed to convert property value of type
    //      'java.lang.String' to required type 'int' for property 'punchDayCnt';
    //      nested exception is java.lang.NumberFormatException: For input string: \"\"",
    var params = {
      "authId": UserRepository.getInstance().authId ?? "",
      "groupid": groupid ?? "",
      "hsn": uploadBean.getHsnSplitStr() ?? "",
      "name": uploadBean?.name?.trim() ?? "",
      "roleid": uploadBean?.getIdentityIdStr() ?? "",
      "city": uploadBean?.cityId ?? "",
      //班级id
      "classids": uploadBean?.classIds() ?? "",
      "companyid":
          UserRepository.getInstance().userData?.companyInfo?.companyid ?? "",
      "courseids": "",
      // "addCbids":uploadBean?.cbid?.toString()??"",
      "addCbids":uploadBean?.addCbids?.toString() ?? "",
      "removeCbids": uploadBean?.removeCbids?.toString() ?? "",
      // "createuid": uploadBean?.createuid,
      "departmentid": uploadBean?.departmentId ?? "",
      "fuid": uploadBean?.fuid,
      "fid": uploadBean?.fid ?? "",
      "napicurl": uploadBean?.headFaceUrl ?? "",
      "nick": uploadBean?.nick ?? "",
      "number": uploadBean?.userNumber ?? "",
      "phone": globalSubPhone(uploadBean?.phone) ?? "",
      "projectid": uploadBean?.projectId ?? "",
      if (uploadBean.isNewPic())
        "putpicurl": uploadBean?.headFaceUrl ?? "",
      "punchDayCnt": 0,
      // "type": "", //用户状态00标记录入 01app手动添加
      if (StringUtils.isNotEmpty(uploadBean?.userid))
        "userid": uploadBean?.userid
    };
    StringBuffer departmentManageIds = StringBuffer();
    if (uploadBean.departmentList != null) {
      departmentManageIds.write(uploadBean.departmentList.join(','));
    }
    StringBuffer classIds = StringBuffer();
    if (uploadBean.classIdList != null) {
      classIds..write(uploadBean.classIdList.join(','));
    }
    if ((uploadBean.departmentList ?? []).isNotEmpty) {
      params["mDepartmentIds"] = departmentManageIds.toString();
    }
    if ((uploadBean.classIdList ?? []).isNotEmpty) {
      params["mClassIds"] = classIds.toString();
    }

    VgHttpUtils.post(ServerApi.BASE_URL + "app/appEditUser",
        params: params,
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          BaseResponseBean bean = BaseResponseBean.fromMap(val);
          if (bean.code == _USER_REPEAT) {
            if (onPushNameRepeat != null) {
              onPushNameRepeat.call();
            } else {
              throw UnimplementedError();
            }
            return;
          }
          if (bean.code == _PHONE_REPEAT) {
            VgToastUtils.toast(context, "用户已存在");
            return;
          }
          if (bean.code == _NICK_REPEAT) {
            VgToastUtils.toast(context, "昵称已存在");
            return;
          }
          VgToastUtils.toast(context, "保存成功");
          String currentPhone = UserRepository.getInstance().getPhone();
          String currentUserId = UserRepository.getInstance().userData?.user?.userid;
          //当前用户修改自己的手机号码需要退出登录
          if(uploadBean.userid == currentUserId && currentPhone != (globalSubPhone(uploadBean?.phone)??"") && logout != null){
            logout.call();
            return;
          }
          VgEventBus.global.send(CompanyNumBarEventMonitor(delete: false));
          if(uploadBean?.headFaceUrl!="" && uploadBean?.headFaceUrl!=null){
            VgEventBus.global.send(new ArtificialAttendanceUpdateEvent());
          }else{
            VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg:'编辑员工'));
          }
          VgEventBus.global.send(new PersonDetailGroupRefreshEvent());
          VgEventBus.global.send(ChangeTabEvent(type: uploadBean?.groupBean?.groupType));
          if(onSuccess != null){
            onSuccess.call();
          }else{
            RouterUtils.pop(context, result: true);
          }
          //是否是当前用户
          if (uploadBean.userid == currentUserId) {
            //自动更新数据
            UserRepository.getInstance()
                .loginService(isBackIndexPage: false)
                .autoLogin();
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  ///更改成功，进行自动登录
  void _autoLogin(BuildContext context) {
    UserRepository.getInstance()
        .loginService(
        isBackIndexPage: false,
        callback: VgBaseCallback(onSuccess: (UserDataBean userDataBean) {
          VgHudUtils.hide(context);
          RouterUtils.pop(context, result: true);
          // VgToastUtils.toast(AppMain.context, "公司切换成功");
        }, onError: (String msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }))
        .autoLogin();
  }
}